//
//  NewsDetailTableViewCell.m
//  item-NetEaseNews-tyw
//
//  Created by tyw on 15/10/2.
//  Copyright (c) 2015年 tyw. All rights reserved.
//

#import "NewsDetailTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "NewsDetailTapImgView.h"
#import "NewsDetailViewController.h"

@implementation NewsDetailTableViewCell {
    UILabel* contentLabel;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.userInteractionEnabled = YES;
        self.backgroundColor = [UIColor clearColor];
        
        contentLabel = [[UILabel alloc] init];
        contentLabel.textColor = [UIColor blackColor];
        contentLabel.numberOfLines = 0;
        contentLabel.tag = 10086;
        contentLabel.font = [UIFont systemFontOfSize:14];
        [self.contentView addSubview:contentLabel];
        //添加单击手势
        contentLabel.userInteractionEnabled = YES;
        UITapGestureRecognizer* tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(linkLabelTapAction)];
        [self addGestureRecognizer:tapGes];
    }
    
    return self;
}

- (void)setImgInfoArray:(NSArray *)imgInfoArray {
    if (_imgInfoArray != imgInfoArray) {
        _imgInfoArray = [imgInfoArray copy];
        
        [self setNeedsLayout];
    }
}

- (void)setContent:(NSString *)content {
    if (![_content isEqualToString:content]) {
        _content = [content copy];
        
        [self setNeedsLayout];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    //文字
    //二话不说， 有些没用的符号除之而后快
    _content = [_content stringByReplacingOccurrencesOfString:@"<br/>" withString:@""];
    _content = [_content stringByReplacingOccurrencesOfString:@"&hellip;" withString:@""];
    
    CGFloat contentHeight = [Tools contentSizeWithMaxWidth:kWidth-20 text:_content fontOfSize:14].height;
    if (contentHeight > 0) {
        [contentLabel setFrame:CGRectMake(10, 5, kWidth-20, contentHeight)];
#warning 富文本实现行间距设置
        NSAttributedString* attributedString = [Tools attributedStrFromStr:_content lineSpace:5];
        contentLabel.textColor = [UIColor blackColor];      //因为复用的问题，这里要重新设为黑色
        [contentLabel setAttributedText:attributedString];
        [contentLabel sizeToFit];
#warning 解析字符串
        //01 如果是推荐阅读，就换颜色，并增加点击事件,跳入推荐阅读的页面
        if (_linkInfoArray.count) {
            if ([_content containsString:@"<!--link"]) {
                //搞清楚跟哪个对应，一个cell只对应一个link推荐阅读,我暂时就这么认为
                NSArray* array = [_content componentsSeparatedByString:@"<!--link"];
                NSString* str1 = array[1];
                NSArray* arr = [str1 componentsSeparatedByString:@"-->"];
                NSString* index = arr[0];       //推荐阅读的序号拿下
                NSString* linkRef = [NSString stringWithFormat:@"<!--link%@-->", index];
                NSDictionary* linkInfoDic = nil;
                for (int i = 0; i < _linkInfoArray.count; i++) {
                    NSString* ref = _linkInfoArray[i][@"ref"];
                    NSArray* refArray = [ref componentsSeparatedByString:@"<!--link"];
                    NSString* refIndex = [(NSString*)refArray[1] componentsSeparatedByString:@"-->"][0];
                    if ([linkRef isEqualToString:[NSString stringWithFormat:@"<!--link%@-->", refIndex]]) {
                        //对上号就对了
                        linkInfoDic = [NSDictionary dictionaryWithDictionary:_linkInfoArray[i]];
                        break;
                    }
                }
                _content = linkInfoDic[@"title"];
                contentLabel.text = _content;
                contentLabel.textColor = [UIColor colorWithRed:63.0/255 green:171.0/255 blue:249.0/255 alpha:1];
            }
        }
        
        //02 如果被<strong></strong>或<b></b>包围，就字体加粗
        //肯定有更多的细节，但我只做到这里了
        if ([_content containsString:@"<strong>"]) {
            //找到被包围的字符串
            NSRange range1 = [_content rangeOfString:@"<strong>"];
            NSRange range2 = [_content rangeOfString:@"</strong>"];
            NSRange range3 = NSMakeRange(range1.location+8, range2.location-range1.location-8); //要加粗的字符串的range
            //字体加粗
            NSMutableAttributedString* newAttr1 = [[Tools attributedStrFromStr:_content lineSpace:5] mutableCopy];
            [newAttr1 addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14]} range:range3];
            _content = [_content stringByReplacingOccurrencesOfString:@"<strong>" withString:@""];
            _content = [_content stringByReplacingOccurrencesOfString:@"</strong>" withString:@"  "];
            NSMutableAttributedString* newAttr2 = [[Tools attributedStrFromStr:_content lineSpace:5] mutableCopy];
            [contentLabel setAttributedText:newAttr2];
        }
        if ([_content containsString:@"</b>"]) {
            //找到被包围的字符串
            NSRange range1 = [_content rangeOfString:@"<b>"];
            NSRange range2 = [_content rangeOfString:@"</b>"];
            NSRange range3 = NSMakeRange(range1.location+3, range2.location-range1.location-3); //要加粗的字符串的range
            //字体加粗
#warning 这里之前是把字符串替换放到字体加粗之前执行的，导致崩溃，数组越界。
            NSMutableAttributedString* newAttr1 = [[Tools attributedStrFromStr:_content lineSpace:5] mutableCopy];
            [newAttr1 addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14]} range:range3];
            _content = [_content stringByReplacingOccurrencesOfString:@"<b>" withString:@""];
            _content = [_content stringByReplacingOccurrencesOfString:@"</b>" withString:@"  "];
            NSMutableAttributedString* newAttr2 = [[Tools attributedStrFromStr:_content lineSpace:5] mutableCopy];
            [contentLabel setAttributedText:newAttr2];
        }
    }
    
    
    
    
    
    //图片们
    //先删除所有的图片再说
    for (UIView* view in self.contentView.subviews) {
        if (view.tag != 10086) {       //不是新闻文字内容，就走你
            [view removeFromSuperview];
        }
    }
    if (_imgInfoArray.count) {      //有图片
        CGFloat y = contentHeight+25+5*(contentHeight/20);
        for (int i = 0; i < _imgInfoArray.count; i++) {
            NSString* pixel = _imgInfoArray[i][@"pixel"];
            NSArray* pixelArray = [pixel componentsSeparatedByString:@"*"];
            CGFloat thisHeight;
#warning 这里pixelArray有可能不存在，如果还这样计算就会崩溃，CALayer bounds contains NaN: [0 nan; 355 nan]:有些尺寸存在0
            if (pixelArray.count) {
                CGFloat oldWidth = [pixelArray[0] floatValue];
                CGFloat oldHeight = [pixelArray[1] floatValue];
                thisHeight = oldHeight/oldWidth*(kWidth-20);
            } else thisHeight = 200;     //如果没有尺寸,默认为200

            NewsDetailTapImgView* imgView = [[NewsDetailTapImgView alloc] initWithFrame:CGRectMake(10, y, kWidth-20, thisHeight)];
            [imgView sd_setImageWithURL:[NSURL URLWithString:_imgInfoArray[i][@"src"]]];
            imgView.contentMode = UIViewContentModeScaleAspectFit;
            imgView.isPhotoSet = NO;        //默认先设置为NO
            imgView.skipId = nil;
            [self.contentView addSubview:imgView];
            y += thisHeight;
            
            //如果是图集，左下角加一个灰色的标记
            NSString* photosetID = _imgInfoArray[i][@"photosetID"];
            if (photosetID.length) {
                UILabel* grayTagLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, thisHeight-30, 40, 30)];
                grayTagLabel.text = @"图集";
                grayTagLabel.textColor = [UIColor whiteColor];
                grayTagLabel.backgroundColor = [UIColor blackColor];
                grayTagLabel.alpha = 0.6;
                grayTagLabel.textAlignment = NSTextAlignmentCenter;
                grayTagLabel.font = [UIFont systemFontOfSize:16];
                [imgView addSubview:grayTagLabel];
                imgView.isPhotoSet = YES;       // 是图集就设置为YES，那边好工作。点击后该干嘛
                imgView.skipId = _imgInfoArray[i][@"photosetID"];
            }
            
            NSString* alt = _imgInfoArray[i][@"alt"];
            if (alt.length) {              //如果有图片说明
                UILabel* altLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, y+5, kWidth-20, 20)];
                altLabel.text = alt;
                altLabel.textColor = [UIColor grayColor];
                altLabel.font = [UIFont systemFontOfSize:13];
                [self.contentView addSubview:altLabel];
                y += 20;
            }
            
            //多张图片之间也应该有间隔
            y += 20;
        }
    }
}

- (void)linkLabelTapAction {
    //遍历数组linkInfoArray，与当前点击的content作对比
    for (NSDictionary* dic in _linkInfoArray) {
        NSString* title = dic[@"title"];
        if ([title isEqualToString:_content]) {
            //根据响应者链找到NewsDetailVC这个类，push到要观看的新闻
            NewsDetailViewController* newsDetailVC = [Tools className:@"NewsDetailViewController" fromResponder:self.nextResponder];
            if (newsDetailVC) {
                NewsDetailViewController* linkNewsDetailVC = [[NewsDetailViewController alloc] init];
                linkNewsDetailVC.newsId = dic[@"id"];
                [newsDetailVC.navigationController pushViewController:linkNewsDetailVC animated:YES];
            }
        }
    }
}



@end
